<template>
  <view class="create-plan">
    <view class="form">
      <view class="form-item">
        <view class="label">计划名称</view>
        <input class="input" v-model="form.name" placeholder="请输入计划名称" />
      </view>
      <view class="form-item">
        <view class="label">计划类型</view>
        <wd-radio-group
          v-model="radioValue"
          inline
          shape="button"
          @change="radioChange"
        >
          <wd-radio :value="1">绘本集计划</wd-radio>
          <wd-radio :value="0">自定义计划</wd-radio>
        </wd-radio-group>
      </view>

      <!-- 绘本集计划 -->
      <template v-if="form.type">
        <view class="form-item">
          <view class="label">每天学几个新的</view>
          <wd-input-number v-model="numberValue" @change="handleChange" />
        </view>
        <view class="form-item">
          <view class="label">复习次数</view>
          <wd-picker
            :columns="columns"
            v-model="pickerValue"
            @confirm="handleConfirm"
          />
        </view>
        <view class="form-item">
          <view class="label">绘本集</view>
          <button class="add-btn" @click="addBook">添加绘本集</button>
          <view class="book-list">
            <view v-for="book in form.books" :key="book.id" class="book-item">
              <img :src="book.cover" class="book-cover" />
              <view class="book-title">{{ book.title }}</view>
              <button class="del-btn" @click="removeBook(book.id)">删除</button>
            </view>
          </view>
        </view>
        <view class="tip">
          *预计每天最多阅读 <text class="highlight">{{ maxBooks }}</text> 本
        </view>
      </template>

      <!-- 自定义计划 -->
      <template v-else>
        <!-- <view class="divider">每日安排</view> -->
        <view v-for="(day, idx) in bookData" :key="idx" class="day-section">
          <view class="day-title"
            >第{{ idx + 1 }}/{{ bookData.length }}天</view
          >
          <view class="plus-card-list">
            <view class="plus-card" @click="toAdd(idx)">
              <view class="plus-icon">+</view>
            </view>
          </view>
        </view>
        <button class="add-day-btn" @click="addDay">增加一天</button>
      </template>

      <view class="actions">
        <button class="save-btn" @click="save">保存</button>
        <button
          v-if="form.type === 'bookset'"
          class="preview-btn"
          @click="preview"
        >
          保存并预览
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";

const form = reactive({
  name: "",
  type: 0,
  newCount: 1,
  reviewIndex: 0,
  books: [],
  data: [],
});


const bookData = ref([])

const radioValue = ref<number>(0);
const numberValue = ref<number>(2);
const columns = ref([
  "不复习",
  "1次（第2天）",
  "2次（第2、5天）",
  "3次（第2、5、8天）",
  "4次（第2、5、8、16天）",
  "5次（第2、5、8、16、31天）",
]);
const pickerValue = ref("不复习");

const maxBooks = computed(() => form.newCount);

onMounted(() => {
  uni.getStorage({
    key: 'books',
    success: (res) => {
      console.log("@@@", res.data);
      
      if(res.data) {

      } else {
        bookData.value = res.data
      }
    }
  })
})
onShow(() => {
  uni.getStorage({
    key: 'books',
    success: (res) => {
      console.log("@@@", res.data);
      
      if(res.data) {

      } else {
        bookData.value = res.data
      }
    }
  })
})
function handleChange({ value }) {
  console.log(value);
}
// const goBack = () => {
//   uni.navigateBack()
// }
function handleConfirm({ value }) {
  value.value = value;
}
const radioChange = ({ value }) => {
  console.log(value);
  radioValue.value = value;
  form.type = value;
};

const changeCount = (delta: number) => {
  if (form.newCount + delta >= 1) form.newCount += delta;
};

const addBook = () => {
  // 这里弹出选择绘本集的逻辑
  form.books.push({
    id: Date.now(),
    title: "New Trainers",
    cover: "/static/images/book1.svg",
  });
};

const toAdd = (idx) => {
  uni.setStorage({
    key: 'books',
    data: bookData.value
  })
  uni.setStorage({
    key: 'idx',
    data: idx
  })
  toLink('/pages-sub/task/addBook')
}

const removeBook = (id: number) => {
  const index = form.books.findIndex((book) => book.id === id);
  if (index > -1) form.books.splice(index, 1);
};

const addDay = () => {
  const data = [];
  bookData.value.push(data);
  console.log(form);
};

const addBookToDay = (idx: number) => {
  // form.days[idx].push({
  //   id: idx,
  // });
  
  console.log(form);
};

const removeBookFromDay = (dayIdx: number, bookId: number) => {
  const day = form.days[dayIdx];
  const index = day.books.findIndex((book) => book.id === bookId);
  if (index > -1) day.books.splice(index, 1);
};

const save = () => {
  if (!form.name.trim()) {
    uni.showToast({ title: "请输入计划名称", icon: "none" });
    return;
  }
  if (form.type === "bookset" && form.books.length === 0) {
    uni.showToast({ title: "请添加绘本集", icon: "none" });
    return;
  }
  if (form.type === "custom") {
    const hasBooks = form.days.some((day) => day.books.length > 0);
    if (!hasBooks) {
      uni.showToast({ title: "请为至少一天添加绘本", icon: "none" });
      return;
    }
  }
  uni.showToast({ title: "保存成功", icon: "success" });
  setTimeout(() => {
    uni.navigateBack();
  }, 1500);
};

const preview = () => {
  save();
  uni.showToast({ title: "预览功能开发中", icon: "none" });
};

const toLink = (url) => {
  uni.navigateTo({ url });
}
</script>

<style scoped>
.create-plan {
  background: #f8f8f8;
  min-height: 100vh;
}
.header {
  display: flex;
  align-items: center;
  padding: 24rpx 0 24rpx 16rpx;
  background: #fff;
}
.back {
  font-size: 40rpx;
  margin-right: 24rpx;
  cursor: pointer;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
}
.form {
  background: #fff;
  border-radius: 16rpx;
  margin: 32rpx;
  padding: 32rpx;
}
.form-item {
  margin-bottom: 32rpx;
}
.label {
  font-size: 28rpx;
  margin-bottom: 12rpx;
}
.input {
  width: 100%;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 16rpx;
  font-size: 28rpx;
}
.radio-group {
  display: flex;
  gap: 32rpx;
}
.radio {
  display: flex;
  align-items: center;
  gap: 8rpx;
}
.stepper {
  display: flex;
  align-items: center;
  gap: 8rpx;
}
.step-input {
  width: 60rpx;
  text-align: center;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 8rpx;
}
.select-wrapper {
  width: 100%;
}
.select {
  padding: 8rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: 1px solid #eee;
  width: 100%;
}
.add-btn,
.del-btn,
.add-day-btn {
  margin-left: 8rpx;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  border: none;
  background: #e6f0ff;
  color: #1976d2;
  font-size: 28rpx;
}
.add-day-btn {
  margin-top: 16rpx;
  width: 100%;
}
.book-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-top: 8rpx;
}
.book-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f5f5f5;
  border-radius: 8rpx;
  padding: 8rpx 12rpx;
}
.book-cover {
  width: 80rpx;
  height: 100rpx;
  border-radius: 8rpx;
}
.book-title {
  font-size: 24rpx;
  margin: 8rpx 0;
}
.tip {
  color: #888;
  font-size: 24rpx;
  margin: 16rpx 0;
}
.highlight {
  color: #1976d2;
  font-weight: bold;
}
.divider {
  font-size: 28rpx;
  color: #1976d2;
  margin: 24rpx 0 8rpx 0;
}
.day-section {
  margin-bottom: 32rpx;
}
.day-title {
  font-weight: bold;
  margin-bottom: 8rpx;
}
.plus-card-list {
  display: flex;
  justify-content: flex-start;
  margin-top: 8rpx;
  gap: 16rpx;
}
.plus-card {
  width: 164rpx;
  height: 196rpx;
  border-radius: 8rpx;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 12rpx 0 rgba(0, 0, 0, 0.08);
  margin-bottom: 8rpx;
}
.plus-icon {
  font-size: 40rpx;
  color: #999;
}
.actions {
  margin-top: 40rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}
.save-btn,
.preview-btn {
  width: 100%;
  padding: 16rpx 0;
  border-radius: 8rpx;
  border: none;
  font-size: 32rpx;
}
.save-btn {
  background: #1976d2;
  color: #fff;
}
.preview-btn {
  background: #4caf50;
  color: #fff;
}
</style>